package com.wolfalpha.utron.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;

import com.wolfalpha.utron.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 方向GirdView列表适配器
 * <p/>
 * Created by luodon on 15/8/27.
 */
public class IdeaDirAdapter extends BaseAdapter {


    private LayoutInflater inflater;

    private List<String> texts;

    boolean singleChoose = false;   //单选

    public IdeaDirAdapter(Context context, List<String> rs, boolean single) {
        singleChoose = single;
        inflater = LayoutInflater.from(context);
        texts = rs;
    }

    private List<Integer> selects = new ArrayList<Integer>();


    @Override
    public int getCount() {
        return texts.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_dir, null);
            viewHolder = new ViewHolder();
            viewHolder.tvContent = (CheckBox) convertView.findViewById(R.id.item_tv_dir);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //设置控件内容
        viewHolder.tvContent.setText(texts.get(position));
        viewHolder.tvContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!selects.contains(position)) {
                    if (singleChoose) selects.clear();
                    selects.add(position);
                    notifyDataSetChanged();
                } else {
                    if (!singleChoose)
                        selects.remove(new Integer(position));
                    notifyDataSetChanged();
                }
                if (mListener != null) {
                    mListener.finish(position);
                }
            }
        });

        if (selects.contains(position)) {
            viewHolder.tvContent.setChecked(true);
        } else {
            viewHolder.tvContent.setChecked(false);
        }

        return convertView;
    }

    private OnFinishedListener mListener;

    public void setOnFinishedListener(OnFinishedListener listener) {
        mListener = listener;
    }


    public interface OnFinishedListener {
        public void finish(int select);
    }

    /**
     * 控件
     */
    class ViewHolder {
        private CheckBox tvContent;
    }

    /**
     * 获取选中的
     *
     * @return
     */
    public List<Integer> getSelected() {
        return selects;
    }
}
